package com.ask.mq.consumer;

import com.ask.entity.VoucherOrder;
import com.ask.entity.VoucherOrderMessage;
import com.ask.service.businessService.ISecKillVoucherService;
import com.ask.service.businessService.IVoucherOrderService;
import com.ask.utils.RedisIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class VoucherOrderMessageConsumer {
    @Autowired
    private ISecKillVoucherService secKillVoucherService;
    @Autowired
    private IVoucherOrderService orderService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private RedisTemplate redisTemplate;

    @KafkaListener(topics = "voucher-order", groupId = "voucher-order-consumer-group" )
    @Transactional
    public void handleVoucherOrderMessage(@Payload VoucherOrderMessage message) {
        // 提取订单信息
        Long orderId = redisIdWorker.nextId("order"); // 生成订单id
        Long voucherId = message.getVoucherId();
        Long userId = message.getUserId();

        log.info("生产者准备处理用户{}发送过来的优惠卷{}的订单", userId, voucherId);

        // 跟新优惠卷库存
        boolean success = secKillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0)
                .update();
        if (!success) {
            log.error("库存不足！");
            redisTemplate.opsForValue().increment("seckill:stock:" + voucherId, 1);
            return;
        }

        // 新增订单表
        VoucherOrder order = VoucherOrder.builder()
                .id(orderId)
                .userId(userId)
                .voucherId(voucherId)
                .build();

        orderService.save(order);
    }
}
